package com.wanmait.hr.util;

import org.springframework.util.StringUtils;

import java.beans.PropertyEditorSupport;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
//处理时间格式
public class TimestampEditor extends PropertyEditorSupport
{
    private final DateFormat dateFormat;

    public TimestampEditor() {
        this.dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    }

    public TimestampEditor(String pattern) {
        this.dateFormat = new SimpleDateFormat(pattern);

    }

    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        if (!StringUtils.hasText(text)) {

            setValue(null);
        }

        else {
            try {
                setValue(new Timestamp(this.dateFormat.parse(text).getTime()));
            }
            catch (ParseException ex) {
                throw new IllegalArgumentException("Could not parse date: " + ex.getMessage(), ex);
            }
        }
    }


    @Override
    public String getAsText() {
        Timestamp value = (Timestamp) getValue();
        return (value != null ? this.dateFormat.format(value) : "");
    }


}
